package com.tiamosu.databinding.page

import android.os.Bundle
import android.view.View
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.tiamosu.navigation.page.FlySupportActivity

/**
 * @author tiamosu
 * @date 2021/5/9
 */
abstract class FlyDataBindingActivity : FlySupportActivity() {

    protected abstract fun getDataBindingConfig(): DataBindingConfig

    private var binding: ViewDataBinding? = null
    protected var rootView: View? = null
        private set

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView()?.also { rootView = it }
    }

    /**
     * 可自定义布局视图生成
     */
    open fun setContentView(): View? {
        val layoutId = getDataBindingConfig().layoutId
        if (layoutId <= 0) {
            return null
        }
        DataBindingUtil.setContentView<ViewDataBinding>(this, layoutId)?.apply {
            binding = this
            lifecycleOwner = this@FlyDataBindingActivity
            getDataBindingConfig().bindingParams.forEach { key, value -> setVariable(key, value) }
        }
        return binding?.root
    }

    override fun onDestroy() {
        super.onDestroy()
        binding?.unbind()
        binding = null
        rootView = null
    }
}